//
//  MarsAddressBookManager.m
//  WKWebDemo
//
//  Created by yangpenghua on 2018/3/27.
//  Copyright © 2018年 linzi. All rights reserved.
//

#import "MarsAddressBookManager.h"

#import <UIKit/UIKit.h>

#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import <AddressBookUI/AddressBookUI.h>



@implementation MarsAddressBookManager

/** 访问通讯录 */
- (void)mars_accessAddressBookResult:(MarsAddressBookAccessBlock)accessAddressResult{
    if (accessAddressResult) {
        self.addressBookAccessAccomplish = accessAddressResult;
    }
    
    //  通讯录认证
    [self CheckAddressBookAuthorization:^(bool isAuthorized, bool isUp_ios_9) {
        if (isAuthorized) {
            //  允许访问通讯录
            [self accessAddressBook];
        } else {
            //  跳转设置通讯录授权
            self.addressBookAccessAccomplish(NO, nil);
        }
    }];
}


#pragma mark 获取通讯录
- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized , bool isUp_ios_9))block{
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 9.0) {
        CNContactStore * contactStore = [[CNContactStore alloc]init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * __nullable error) {
                if (error)
                {
                    NSLog(@"Error: %@", error);
                }
                else if (!granted)
                {
                    
                    block(NO,YES);
                }
                else
                {
                    block(YES,YES);
                }
            }];
        } else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){
            block(YES,YES);
        } else {
            block(NO,YES);
        }
    }else {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        
        if (authStatus == kABAuthorizationStatusNotDetermined)
        {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error)
                    {
                        NSLog(@"Error: %@", (__bridge NSError *)error);
                    }
                    else if (!granted)
                    {
                        
                        block(NO,NO);
                    }
                    else
                    {
                        block(YES,NO);
                    }
                });
            });
        } else if (authStatus == kABAuthorizationStatusAuthorized){
            block(YES,NO);
        } else {
            block(NO,NO);
        }
    }
}

#pragma mark 通讯录操作
- (void)accessAddressBook
{
    NSString *addressBookStr = @"";
    //创建通讯簿的引用
    ABAddressBookRef addBook = ABAddressBookCreateWithOptions(NULL, NULL);
    //获取所有联系人的数组
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    //获取联系人总数
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    //进行遍历
    for (NSInteger i=0; i<number; i++) {
        //获取联系人对象的引用
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        //获取当前联系人姓氏
        NSString*firstName=(__bridge NSString *)(ABRecordCopyValue(people,kABPersonLastNameProperty));
        //获取当前联系人名字
        NSString*lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        firstName = [self isEmptyString:firstName]?@"":firstName;
        lastName = [self isEmptyString:lastName]?@"":lastName;
        NSString *name = [NSString stringWithFormat:@"%@%@",firstName,lastName];
        NSString *filterName = [self filterSpecialSymbol:name];
        if (filterName.length < 1) {
            filterName = @"xxx";
        }
        
        //获取当前联系人的电话 数组
        NSMutableArray * phoneArr = [[NSMutableArray alloc]init];
        ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (NSInteger j=0; j<ABMultiValueGetCount(phones); j++) {
            [phoneArr addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))];
        }
        NSString *phoneStr = [phoneArr componentsJoinedByString:@"&"];
        if (phoneStr.length < 1) {
            phoneStr = @"xxx";
        }
        NSString *personStr = [NSString stringWithFormat:@"%@:%@", filterName,phoneStr];
        if (i != (number - 1)) {
            personStr = [personStr stringByAppendingString:@","];
        }
        addressBookStr = [addressBookStr stringByAppendingString:personStr];
        
    }
    
    //  通讯录结果
    addressBookStr = [[addressBookStr stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    //  回调通讯访问结果
    if (self.addressBookAccessAccomplish) {
        self.addressBookAccessAccomplish(YES, addressBookStr);
    }
}

- (NSString *)filterSpecialSymbol:(NSString *)filterStr{
    if (filterStr == nil) {
        return @"";
    }
    NSString *resultStr = [filterStr stringByReplacingOccurrencesOfString:@"," withString:@""];
    resultStr = [resultStr stringByReplacingOccurrencesOfString:@":" withString:@""];
    resultStr = [resultStr stringByReplacingOccurrencesOfString:@"&" withString:@""];
    return resultStr;
}


#pragma mark 判断字符串是否为空
- (BOOL)isEmptyString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}


@end
